package in.choich.transaction;

import java.util.HashMap;
import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

import com.atomikos.jdbc.AtomikosDataSourceBean;

import in.choich.transaction.xDatasource.XDatasourceConfig;

//import com.mysql.cj.jdbc.MysqlXADataSource;

@Configuration
@DependsOn("transactionManager")
@EnableJpaRepositories(basePackages = "in.choich.repositories.jpa", entityManagerFactoryRef = "primaryEntityManager", transactionManagerRef = "transactionManager")
public class PrimaryDatasourceConfig {

	@Autowired
	private JpaVendorAdapter jpaVendorAdapter;


	@Autowired
	private XDatasourceConfig xDatasourceConfig;

	@Bean(name = "primaryEntityManager")
	@DependsOn("transactionManager")
	@Primary
	public LocalContainerEntityManagerFactoryBean primaryEntityManager() throws Throwable {

		HashMap<String, Object> properties = new HashMap<String, Object>();
		properties.put("hibernate.transaction.jta.platform", AtomikosJtaPlatform.class.getName());
		properties.put("javax.persistence.transactionType", "JTA");

		LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
		entityManager.setJtaDataSource(xDatasourceConfig.primaryDataSource());
		entityManager.setJpaVendorAdapter(jpaVendorAdapter);
		entityManager.setPackagesToScan("in.choich.entities.jpa");
		entityManager.setPersistenceUnitName("mysql_1_PersistenceUnit");
		entityManager.setJpaPropertyMap(properties);
		return entityManager;
	}

}
